package com.jgy.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jgy.entity.SpaceUser;
import com.jgy.mapper.SpaceUserMapper;
import com.jgy.security.model.AuthParamsDto;
import com.jgy.security.model.XcUserExt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 姜光远
 * @date 2023/2/24 16:27
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService{

    @Autowired
    private SpaceUserMapper userMapper;
    @Lazy
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override

    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //账号
        String username = authParamsDto.getUsername();
        SpaceUser user = userMapper.selectOne(new LambdaQueryWrapper<SpaceUser>().eq(SpaceUser::getUsername, username));
        if(user==null){
            //返回空表示用户不存在
            throw new RuntimeException("账号不存在");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(user,xcUserExt);
        //校验密码
        //取出数据库存储的正确密码
        String passwordDb  =user.getPassword();
        String passwordForm = authParamsDto.getPassword();
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if(!matches){
            throw new RuntimeException("账号或密码错误");
        }
        return xcUserExt;
    }

}
